package com.gscitysfy.cus.drain.modules.command.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gscitysfy.cloudfrmwk.security.definition.core.HerodotusUserDetails;
import com.gscitysfy.cloudfrmwk.security.utils.SecurityUtils;
import com.gscitysfy.cus.drain.config.BusinessException;
import com.gscitysfy.cus.drain.modules.command.convert.DangerSituationManageConvert;
import com.gscitysfy.cus.drain.modules.command.dto.*;
import com.gscitysfy.cus.drain.modules.command.entity.DangerSituationManage;
import com.gscitysfy.cus.drain.modules.command.entity.InstructCar;
import com.gscitysfy.cus.drain.modules.command.entity.InstructTeam;
import com.gscitysfy.cus.drain.modules.command.entity.InstructWarehouse;
import com.gscitysfy.cus.drain.modules.command.mapper.DangerSituationManageMapper;
import com.gscitysfy.cus.drain.modules.command.service.IDangerSituationManageService;
import com.gscitysfy.cus.drain.modules.command.service.IInstructCarService;
import com.gscitysfy.cus.drain.modules.command.service.IInstructTeamService;
import com.gscitysfy.cus.drain.modules.command.service.InstructWarehouseService;
import com.gscitysfy.cus.drain.modules.command.vo.DangerSituationManageQuery;
import com.gscitysfy.cus.drain.modules.common.entity.DrainInspectionMnFile;
import com.gscitysfy.cus.drain.modules.common.service.IFileService;
import com.gscitysfy.cus.drain.modules.resource.dto.DrainBaseMnWarehouseDto;
import com.gscitysfy.cus.drain.modules.resource.dto.ResourceCarDto;
import com.gscitysfy.cus.drain.modules.resource.dto.ResourceTeamDto;
import com.gscitysfy.cus.drain.modules.resource.service.IDrainBaseMnWarehouseService;
import com.gscitysfy.cus.drain.modules.resource.service.IResourceCarService;
import com.gscitysfy.cus.drain.modules.resource.service.IResourceTeamService;
import com.gscitysfy.cus.drain.utils.DateUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Administrator
 * @since 2022-10-20 21:01:08
 */
@AllArgsConstructor
@Service
public class DangerSituationManageServiceImpl extends ServiceImpl<DangerSituationManageMapper, DangerSituationManage> implements IDangerSituationManageService {

    private final IResourceCarService iResourceCarService;
    private final IResourceTeamService iResourceTeamService;
    private final IDrainBaseMnWarehouseService iDrainBaseMnWarehouseService;

    private final IInstructCarService iInstructCarService;
    private final IInstructTeamService iInstructTeamService;
    private final InstructWarehouseService instructWarehouseService;

    private final IFileService iFileService;

    private final DangerSituationManageMapper dangerSituationManageMapper;

    private final DangerSituationManageConvert dangerSituationManageConvert;

    @Override
    public IPage<DangerSituationManageDto> fetchPage(Page page, DangerSituationManageQuery query) {
        LambdaQueryWrapper<DangerSituationManage> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper = buildQueryWrapper(queryWrapper, query);
        Page<DangerSituationManage> dangerSituationManagePage = this.page(page, queryWrapper);
        return dangerSituationManagePage.convert(dangerSituationManageConvert::toDto);
    }

    @Override
    public DangerSituationManageDto fetchById(Long cmKid) {
        DangerSituationManage dangerSituationManage = baseMapper.selectById(cmKid);
        DangerSituationManageDto dangerSituationManageDto = dangerSituationManageConvert.toDto(dangerSituationManage);
        //获取应急车队
        List<InstructCar> instructCarList = iInstructCarService.fetchByDangerSituation(cmKid);
        if (CollectionUtils.isNotEmpty(instructCarList)) {
            List<Long> carIdList = instructCarList.stream().map(InstructCar::getCarId).distinct().collect(Collectors.toList());
            List<ResourceCarDto> resourceCarDtoList = iResourceCarService.fetchInIdList(carIdList);
            dangerSituationManageDto.setResourceCarDtoList(resourceCarDtoList);
        }
        //应急队伍
        List<InstructTeam> instructTeamList = iInstructTeamService.fetchByDangerSituation(cmKid);
        if (CollectionUtils.isNotEmpty(instructTeamList)) {
            List<Long> teamIdList = instructTeamList.stream().map(InstructTeam::getTeamId).distinct().collect(Collectors.toList());
            List<ResourceTeamDto> resourceTeamDtoList = iResourceTeamService.fetchInIdList(teamIdList);
            dangerSituationManageDto.setResourceTeamDtoList(resourceTeamDtoList);
        }
        //应急物资
        List<InstructWarehouse> instructWarehouseList = instructWarehouseService.fetchByDangerSituation(cmKid);
        if (CollectionUtils.isNotEmpty(instructWarehouseList)) {
            List<Long> warehouseIdList = instructWarehouseList.stream().map(InstructWarehouse::getWarehouseId).distinct().collect(Collectors.toList());
            List<DrainBaseMnWarehouseDto> drainBaseMnWarehouseDtoList = iDrainBaseMnWarehouseService.fetchInIdList(warehouseIdList);
            dangerSituationManageDto.setDrainBaseMnWarehouseDtoList(drainBaseMnWarehouseDtoList);
        }
        return dangerSituationManageDto;
    }

    @Override
    public DangerSituationProcessingDto processing(Long cmKid) {

        DangerSituationProcessingDto dangerSituationProcessingDto = new DangerSituationProcessingDto();
        dangerSituationProcessingDto.setDangerSituationId(cmKid);
        List<ProcessingDto> processingDtoList = new ArrayList<>();
        DangerSituationManage dangerSituationManage = baseMapper.selectById(cmKid);
        processingDtoList.add(ProcessingDto
                .builder()
                .content("发现险情")
                .timestamp(Objects.nonNull(dangerSituationManage.getDiscoveryTime())
                        ? DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()).format(dangerSituationManage.getDiscoveryTime())
                        : null)
                .build());
        processingDtoList.add(ProcessingDto
                .builder()
                .content("启动预案")
                .timestamp(Objects.nonNull(dangerSituationManage.getReservePlanTime())
                        ? DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()).format(dangerSituationManage.getReservePlanTime())
                        : null)
                .build());
        processingDtoList.add(ProcessingDto
                .builder()
                .content("确定资源调度方案")
                .timestamp(Objects.nonNull(dangerSituationManage.getResourceDispatchTime())
                        ? DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()).format(dangerSituationManage.getResourceDispatchTime())
                        : null)
                .build());
        dangerSituationProcessingDto.setProcessingDtoList(processingDtoList);

        //小程序回显
        List<AppletInstructDto> appletInstructDtoList = new ArrayList<>();
        //获取应急车队
        List<InstructCar> instructCarList = iInstructCarService.fetchByDangerSituation(cmKid);
        if (CollectionUtils.isNotEmpty(instructCarList)) {
            instructCarList.forEach(instructCar -> {
                ResourceCarDto resourceCarDto = iResourceCarService.getById(instructCar.getCarId());
                DrainInspectionMnFile file = iFileService.getFileById(instructCar.getFileId());
                appletInstructDtoList.add(AppletInstructDto
                        .builder()
                        .cmKid(instructCar.getCmKid())
                        .instructTime(instructCar.getCmAddtime())
                        .type("CAR")
                        .name(Objects.nonNull(resourceCarDto) ? resourceCarDto.getCarName() : null)
                        .status(instructCar.getStatus())
                        .closeFlag(instructCar.getCloseFlag())
                        .problemDetail(instructCar.getProblemDetail())
                        .fileUrl(Objects.nonNull(file) ? file.getCmFilePreviewUrl() : null)
                        .phone(resourceCarDto.getPhone())
                        .build());
            });
        }
        //应急队伍
        List<InstructTeam> instructTeamList = iInstructTeamService.fetchByDangerSituation(cmKid);
        if (CollectionUtils.isNotEmpty(instructTeamList)) {
            instructTeamList.forEach(instructTeam -> {
                ResourceTeamDto resourceTeamDto = iResourceTeamService.getById(instructTeam.getTeamId());
                DrainInspectionMnFile file = iFileService.getFileById(instructTeam.getFileId());
                appletInstructDtoList.add(AppletInstructDto
                        .builder()
                        .cmKid(instructTeam.getCmKid())
                        .instructTime(instructTeam.getCmAddtime())
                        .type("TEAM")
                        .name(Objects.nonNull(resourceTeamDto) ? resourceTeamDto.getTeamName() : null)
                        .status(instructTeam.getStatus())
                        .closeFlag(instructTeam.getCloseFlag())
                        .problemDetail(instructTeam.getProblemDetail())
                        .fileUrl(Objects.nonNull(file) ? file.getCmFilePreviewUrl() : null)
                        .phone(resourceTeamDto.getPhone())
                        .build());
            });
        }
        dangerSituationProcessingDto.setAppletInstructDtoList(appletInstructDtoList);
        return dangerSituationProcessingDto;
    }

    @Override
    public Map<String, Long> dashboard() {
        Map<String, Long> map = new HashMap<>(7);
        //应急车辆
        List<ResourceCarDto> resourceCarDtoList = iResourceCarService.fetchGis();
        long assignedCarCount = resourceCarDtoList.stream().filter(ResourceCarDto::getAssignedFlag).count();
        map.put("assignedCarCount", assignedCarCount);
        long unAssignedCarCount = resourceCarDtoList.stream().filter(c -> !c.getAssignedFlag()).count();
        map.put("unAssignedCarCount", unAssignedCarCount);

        //应急队伍
        List<ResourceTeamDto> resourceTeamDtoList = iResourceTeamService.fetchGis();
        long assignedTeamCount = resourceTeamDtoList.stream().filter(ResourceTeamDto::getAssignedFlag).count();
        map.put("assignedTeamCount", assignedTeamCount);
        long unAssignedTeamCount = resourceTeamDtoList.stream().filter(t -> !t.getAssignedFlag()).count();
        map.put("unAssignedTeamCount", unAssignedTeamCount);

        //险情派单关闭量查询
        DangerSituationManageQuery query = new DangerSituationManageQuery();
        query.setCmUsable(false);
        LambdaQueryWrapper<DangerSituationManage> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper = buildQueryWrapper(queryWrapper, query);
        List<DangerSituationManage> dangerSituationManageList = baseMapper.selectList(queryWrapper);
        //派单
        long dispatchCount = dangerSituationManageList.stream().filter(DangerSituationManage::getDispatchFlag).count();
        map.put("dispatchCount", dispatchCount);
        //未派单
        long unDispatchCount = dangerSituationManageList.stream().filter(s -> !s.getDispatchFlag()).count();
        map.put("unDispatchCount", unDispatchCount);
        //已关闭
        long closeCount = dangerSituationManageList.stream().filter(DangerSituationManage::getCloseFlag).count();
        map.put("closeCount", closeCount);

        return map;
    }
    @Override
    public List<StatisticalData> getQXCDList(String dimon,String startDate,String endDate){
        List<StatisticalData>  resultList = new ArrayList<>();
        List<String> timeBetweenDate = new ArrayList<String>();


        if ("month".equals(dimon)){
            timeBetweenDate = DateUtil.getMonthBetweenDate(startDate, endDate);
        }
        if ("year".equals(dimon)){
            timeBetweenDate = DateUtil.getYearBetweenDate(startDate, endDate);
        }
        if ("quarter".equals(dimon)){
            timeBetweenDate = DateUtil.getQuarterBetweenDateZQ(startDate, endDate);
        }
        for (String time : timeBetweenDate) {
            StatisticalData statisticalData = new StatisticalData();
            statisticalData.setTime(time);
            statisticalData.setTotal(0);
            resultList.add(statisticalData);
        }
        List<StatisticalData> mapperList =  dangerSituationManageMapper.getQXCDList(dimon);
        if (CollectionUtils.isEmpty(mapperList)){
            return resultList;
        }
        for (StatisticalData statisticalData : mapperList) {
            for (StatisticalData data : resultList) {
                String time = "";
                if ("month".equals(dimon)){
                    time = statisticalData.getMonthDiemon();
                }
                if ("year".equals(dimon)){
                    time = statisticalData.getYearDiemon();
                }
                if ("quarter".equals(dimon)){
                    time = statisticalData.getQuarterDiemon();
                }
                if (time.equals(data.getTime())){
                    data.setTotal(statisticalData.getTotal());
                    data.setCarTotal(statisticalData.getCarTotal());
                    data.setTeamTotal(statisticalData.getTeamTotal());
                    data.setPersonTotal(statisticalData.getPersonTotal());
                }
            }
        }
        return resultList;
    }
    @Override
    public List<DangerSituationManageDto> fetchGis() {
        //险情派单关闭量查询
        DangerSituationManageQuery query = new DangerSituationManageQuery();
        query.setCmUsable(false);
        query.setPublishStatus("1");
        LambdaQueryWrapper<DangerSituationManage> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper = buildQueryWrapper(queryWrapper, query);
        List<DangerSituationManage> dangerSituationManageList = baseMapper.selectList(queryWrapper);
        return dangerSituationManageConvert.toDtoList(dangerSituationManageList);
    }
    @Override
    public List<StatisticalData>  getXqTjList(String dimon,String startDate,String endDate) {
        List<StatisticalData>  resultList = new ArrayList<>();
        if ("month".equals(dimon)){
            resultList = getMonthBetweenDate(startDate,endDate);
        }
      if ("year".equals(dimon)){
            resultList = getYearBetweenDate(startDate,endDate);
        }
      if ("quarter".equals(dimon)){
          resultList = getQuarterBetweenDate(startDate,endDate);
      }
        if ("xunqi".equals(dimon)){
            resultList = getXunQiBetweenDate(startDate,endDate);
        }
        return resultList;
    }
    private List<StatisticalData>  getMonthBetweenDate(String startDate,String endDate){


        ArrayList<StatisticalData> resultList = new ArrayList<>();
        List<String> yearBetweenDate = DateUtil.getYearBetweenDate(startDate, endDate);
        List<String> monthBetweenDate = new ArrayList<>();
        for (String year : yearBetweenDate) {
            monthBetweenDate.addAll(DateUtil.getMonthByYear(year));
        }
        for (String time : monthBetweenDate) {
            StatisticalData statisticalData = new StatisticalData();
            statisticalData.setTime(time);
            statisticalData.setTotal(0);
            resultList.add(statisticalData);
        }
        List<StatisticalData> statisticList = new ArrayList<>();
        for (String year : yearBetweenDate) {
            List<StatisticalData> mapperList =  dangerSituationManageMapper.getXqTjListByMouth(year);
            statisticList.addAll(mapperList);
        }


        if (CollectionUtils.isEmpty(statisticList)){
            return resultList;
        }
        for (StatisticalData statisticalData : statisticList) {
            String time = statisticalData.getTime();
            for (StatisticalData data : resultList) {
                if (time.equals(data.getTime())){
                    data.setTotal(statisticalData.getTotal());
                }
            }
        }
        return resultList;
    }
    private List<StatisticalData> getYearBetweenDate(String startDate,String endDate){
        ArrayList<StatisticalData> resultList = new ArrayList<>();
        List<String> monthBetweenDate = DateUtil.getYearBetweenDate(startDate, endDate);
        for (String time : monthBetweenDate) {
            StatisticalData statisticalData = new StatisticalData();
            statisticalData.setTime(time);
            statisticalData.setTotal(0);
            resultList.add(statisticalData);
        }
        List<StatisticalData> mapperList =  dangerSituationManageMapper.getXqTjListByYear(startDate,endDate);
        if (CollectionUtils.isEmpty(mapperList)){
            return resultList;
        }
        for (StatisticalData statisticalData : mapperList) {
            String time = statisticalData.getTime();
            for (StatisticalData data : resultList) {
                if (time.equals(data.getTime())){
                    data.setTotal(statisticalData.getTotal());
                }
            }
        }
        return resultList;
    }

    private List<StatisticalData> getXunQiBetweenDate(String startDate,String endDate){
        ArrayList<StatisticalData> resultList = new ArrayList<>();
        List<String> yearBetweenDate = DateUtil.getYearBetweenDate(startDate, endDate);
        for (String year : yearBetweenDate) {
          String  startTime =  year+"-07-01";
          String  endTime =  year+"-10-01";
            StatisticalData data =  dangerSituationManageMapper.getXqTjListByXunQi(startTime,endTime);
            data.setTime(year);
            resultList.add(data);
        }
        return resultList;
    }


    private List<StatisticalData> getQuarterBetweenDate(String startDate,String endDate){
        ArrayList<StatisticalData> resultList = new ArrayList<>();
        List<String> monthBetweenDate = DateUtil.getQuarterBetweenDate(startDate, endDate);
        for (String time : monthBetweenDate) {
            StatisticalData statisticalData = new StatisticalData();
            statisticalData.setTime(time);
            statisticalData.setTotal(0);
            resultList.add(statisticalData);
        }

        List<StatisticalData> mapperList =  dangerSituationManageMapper.getXqTjListByQuarter(startDate,endDate);
        if (CollectionUtils.isEmpty(mapperList)){
            return resultList;
        }
        for (StatisticalData statisticalData : mapperList) {
            String time = statisticalData.getTime();
            for (StatisticalData data : resultList) {
                if (time.equals(data.getTime())){
                    data.setTotal(statisticalData.getTotal());
                }
            }
        }
        return resultList;
    }




   private List<Map<String, Object>> getMonthBetweenDate2(String dimon,String startDate,String endDate){
       List<String>  monthList = DateUtil.getMonthBetweenDate(startDate,endDate);
       List<Map<String, Object>>  xqTjList= dangerSituationManageMapper.getXqTjList(dimon);
       List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
       for(int i =0;i<monthList.size();i++){
           Map<String,Object> map = new HashMap<>();
           map.put(monthList.get(i),0);
           resultList.add(map);
           for(int j=0;j<xqTjList.size();j++){
               if(xqTjList.get(j).get("monthdiemon").equals(monthList.get(i))){
                   map.put(monthList.get(i),xqTjList.get(j).get("xqsl"));
                   resultList.add(map);
               }
           }
       }
       List newList = resultList.stream().distinct().collect(Collectors.toList());
       return newList;
   }

    @Override
    public List<Map<String, Object>> getXqLXLYTjList(String dimon) {
        List<Map<String, Object>>  xqLXLYTjList=dangerSituationManageMapper.getXqLXLYTjList(dimon);
        return xqLXLYTjList;
    }

    public String  currentCmCode(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String currentCode = sdf.format(date);

        int max=10000;
        int min=1000;
        Random random = new Random();
        String randomMath =  (random.nextInt(max - min) + min + 1)+"";
        String currentDateCode = "RGXQ"+currentCode+randomMath;
        return currentDateCode;
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Boolean alarmGenerate(DangerSituationManageDto dto) {
            DangerSituationManage dangerSituationManage = new DangerSituationManage();
            dangerSituationManageConvert.toEntity(dangerSituationManage, dto);
            dangerSituationManage.setPublishStatus("0");
            return this.save(dangerSituationManage);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Boolean saveOrUpdate(DangerSituationManageDto dto) {
        if (Objects.isNull(dto.getCmKid())) {
            DangerSituationManage dangerSituationManage = new DangerSituationManage();
            dangerSituationManageConvert.toEntity(dangerSituationManage, dto);
            //添加发布人手机号
            HerodotusUserDetails principal = SecurityUtils.getPrincipal();
            if (Objects.nonNull(principal)) {
                dangerSituationManage.setPhone(principal.getPhoneNumber());
            }
            else {
                throw new BusinessException("当前登陆人信息手机号为空");
            }
            dangerSituationManage.setCmCode(currentCmCode());
            dangerSituationManage.setPublishStatus("0");
            return this.save(dangerSituationManage);
        } else {
            DangerSituationManage dangerSituationManage = baseMapper.selectById(dto.getCmKid());
            dangerSituationManageConvert.toEntity(dangerSituationManage, dto);
            if(StringUtils.isNotEmpty(dto.getPublishStatus())&&"1".equals(dto.getPublishStatus())){
                dangerSituationManage.setPublishTime(new Date());
            }
            //添加发布人手机号
            HerodotusUserDetails principal = SecurityUtils.getPrincipal();
            if (Objects.nonNull(principal)) {
                dangerSituationManage.setPhone(principal.getPhoneNumber());
            } else {
                throw new BusinessException("当前登陆人信息手机号为空");
            }
            return this.updateById(dangerSituationManage);
        }
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Boolean delete(List<Long> idList) {
        List<DangerSituationManage> dangerSituationManageList = new ArrayList<>();
        idList.forEach(id -> {
            DangerSituationManage dangerSituationManage = baseMapper.selectById(id);
            //检验险情中应急车辆和应急队伍是否由未完成的指令
//            checkInstructCompletion(id);
            dangerSituationManage.setCmUsable(true);
            dangerSituationManageList.add(dangerSituationManage);
        });
        //查看是否关联资源调度，关联级联删除
        iInstructCarService.deleteBatch(idList);
        iInstructTeamService.deleteBatch(idList);
        instructWarehouseService.deleteBatch(idList);
        return this.updateBatchById(dangerSituationManageList);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Boolean close(List<Long> idList) {
        List<DangerSituationManage> dangerSituationManageList = new ArrayList<>();
        idList.forEach(id -> {
            DangerSituationManage dangerSituationManage = baseMapper.selectById(id);
            //检验险情中应急车辆和应急队伍是否由未完成的指令
            checkInstructCompletion(id);
            dangerSituationManage.setCloseFlag(true);
            dangerSituationManageList.add(dangerSituationManage);
        });
        return this.updateBatchById(dangerSituationManageList);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Long launchPlan(DangerSituationManageDto dto) {
        DangerSituationManage dangerSituationManage = baseMapper.selectById(dto.getCmKid());
        //派单
        dangerSituationManage.setDispatchFlag(true);
        //关联预案
        dangerSituationManage.setReservePlanId(dto.getReservePlanId());
        //预案等级
        dangerSituationManage.setReservePlanLevel(dto.getReservePlanLevel());
        //记录启动预案时间
        dangerSituationManage.setReservePlanTime(LocalDateTime.now());
        this.updateById(dangerSituationManage);
        return dangerSituationManage.getCmKid();
    }



    /**
     * query组装
     *
     * @param queryWrapper
     * @param query
     * @return
     */
    public LambdaQueryWrapper<DangerSituationManage> buildQueryWrapper(LambdaQueryWrapper<DangerSituationManage> queryWrapper, DangerSituationManageQuery query) {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (Objects.nonNull(query.getCmRegflag())) {
            queryWrapper.eq(DangerSituationManage::getCmRegflag, String.valueOf(query.getCmRegflag()));
        }
        if (StringUtils.isNotEmpty(query.getSource())) {
            queryWrapper.eq(DangerSituationManage::getSource, query.getSource());
        }
        if (StringUtils.isNotEmpty(query.getCategory())) {
            queryWrapper.eq(DangerSituationManage::getCategory, query.getCategory());
        }
        if (StringUtils.isNotEmpty(query.getName())) {
            queryWrapper.like(DangerSituationManage::getName, query.getName());
        }
        if (StringUtils.isNotEmpty(query.getAddress())) {
            queryWrapper.like(DangerSituationManage::getAddress, query.getAddress());
        }
        if (Objects.nonNull(query.getDispatchFlag())) {
            queryWrapper.eq(DangerSituationManage::getDispatchFlag, query.getDispatchFlag());
        }
        if (Objects.nonNull(query.getAlarmId())) {
            queryWrapper.eq(DangerSituationManage::getAlarmId, query.getAlarmId());
        }
        if (Objects.nonNull(query.getCloseFlag())) {
            queryWrapper.eq(DangerSituationManage::getCloseFlag, query.getCloseFlag());
        }
        if (StringUtils.isNotEmpty(query.getPublishStatus())) {
            queryWrapper.eq(DangerSituationManage::getPublishStatus, query.getPublishStatus());
        }
        try{
            if (StringUtils.isNotBlank(query.getPublishBeginTime()) && StringUtils.isNotBlank(query.getPublishEndTime())) {
                queryWrapper.ge(DangerSituationManage::getPublishTime, sdf1.parse(query.getPublishBeginTime()));
                queryWrapper.le(DangerSituationManage::getPublishTime, sdf1.parse(query.getPublishEndTime()));
            }
            if (StringUtils.isNotBlank(query.getDiscoveryBeginTime()) && StringUtils.isNotBlank(query.getDiscoveryEndTime())) {
                queryWrapper.ge(DangerSituationManage::getDiscoveryTime, sdf1.parse(query.getDiscoveryBeginTime()));
                queryWrapper.le(DangerSituationManage::getDiscoveryTime, sdf1.parse(query.getDiscoveryEndTime()));
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        //删除标识
        queryWrapper.eq(DangerSituationManage::getCmUsable, query.getCmUsable());
        //更新时间倒排
        queryWrapper.orderByDesc(DangerSituationManage::getCmUptime);
        return queryWrapper;
    }

    /**
     * 检验险情中应急车辆和应急队伍是否由未完成的指令
     *
     * @param dangerSituationId desc //关联车队和队伍只有完成工作或者拒绝才允许删除
     */
    public void checkInstructCompletion(Long dangerSituationId) {
        //车辆
        List<InstructCar> instructCarList = iInstructCarService.fetchByDangerSituation(dangerSituationId);
        List<InstructCar> carResult = instructCarList
                .stream()
                .filter(instructCar -> !instructCar.getCloseFlag())
                .filter(instructCar -> !StringUtils.equals(instructCar.getStatus(), "REFUSE"))
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(carResult)) {
            Long carId = carResult.stream().findFirst().get().getCarId();
            ResourceCarDto resourceCarDto = iResourceCarService.getById(carId);
            throw new BusinessException(String.format("应急车辆：%s，任务暂未处理完成", resourceCarDto.getCarName()));
        }
        //队伍
        List<InstructTeam> instructTeamList = iInstructTeamService.fetchByDangerSituation(dangerSituationId);
        List<InstructTeam> teamResult = instructTeamList
                .stream()
                .filter(instructTeam -> !instructTeam.getCloseFlag())
                .filter(instructTeam -> StringUtils.equals(instructTeam.getStatus(), "REFUSE"))
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(teamResult)) {
            Long teamId = teamResult.stream().findFirst().get().getTeamId();
            ResourceTeamDto resourceTeamDto = iResourceTeamService.getById(teamId);
            throw new BusinessException(String.format("应急队伍：%s，任务暂未处理完成", resourceTeamDto.getTeamName()));
        }
    }


    @Override
    public List<StatisticalData> getQxrwTjList(String dimon, String startDate, String endDate) {
        List<StatisticalData>  resultList = new ArrayList<>();
        if ("month".equals(dimon)){
            resultList = getMonthBetweenDateQxrw(startDate,endDate);
        }
        if ("year".equals(dimon)){
            resultList = getYearBetweenDateQxrw(startDate,endDate);
        }
        if ("quarter".equals(dimon)){
            resultList = getQuarterBetweenDateQxrw(startDate,endDate);
        }
        if ("xunqi".equals(dimon)){
            resultList = getXunQiBetweenDateQxrw(startDate,endDate);
        }
        return resultList;
    }

    private List<StatisticalData>  getMonthBetweenDateQxrw(String startDate,String endDate){
        ArrayList<StatisticalData> resultList = new ArrayList<>();
        List<String> yearBetweenDate = DateUtil.getYearBetweenDate(startDate, endDate);
        List<String> monthBetweenDate = new ArrayList<>();
        for (String year : yearBetweenDate) {
            monthBetweenDate.addAll(DateUtil.getMonthByYear(year));
        }
        for (String time : monthBetweenDate) {
            StatisticalData statisticalData = new StatisticalData();
            statisticalData.setTime(time);
            statisticalData.setTotal(0);
            resultList.add(statisticalData);
        }
        List<StatisticalData> statisticList = new ArrayList<>();
        for (String year : yearBetweenDate) {
            List<StatisticalData> mapperList =  dangerSituationManageMapper.getXqTjListByMouthQxrw(year);
            statisticList.addAll(mapperList);
        }

        if (CollectionUtils.isEmpty(statisticList)){
            return resultList;
        }
        for (StatisticalData statisticalData : statisticList) {
            String time = statisticalData.getTime();
            for (StatisticalData data : resultList) {
                if (time.equals(data.getTime())){
                    data.setTotal(statisticalData.getTotal());
                }
            }
        }
        return resultList;
    }

    private List<StatisticalData> getYearBetweenDateQxrw(String startDate,String endDate){
        ArrayList<StatisticalData> resultList = new ArrayList<>();
        List<String> monthBetweenDate = DateUtil.getYearBetweenDate(startDate, endDate);
        for (String time : monthBetweenDate) {
            StatisticalData statisticalData = new StatisticalData();
            statisticalData.setTime(time);
            statisticalData.setTotal(0);
            resultList.add(statisticalData);
        }
        List<StatisticalData> mapperList =  dangerSituationManageMapper.getXqTjListByYearQxrw(startDate,endDate);
        if (CollectionUtils.isEmpty(mapperList)){
            return resultList;
        }
        for (StatisticalData statisticalData : mapperList) {
            String time = statisticalData.getTime();
            for (StatisticalData data : resultList) {
                if (time.equals(data.getTime())){
                    data.setTotal(statisticalData.getTotal());
                }
            }
        }
        return resultList;
    }

    private List<StatisticalData> getQuarterBetweenDateQxrw(String startDate,String endDate){
        ArrayList<StatisticalData> resultList = new ArrayList<>();
        List<String> monthBetweenDate = DateUtil.getQuarterBetweenDate(startDate, endDate);
        for (String time : monthBetweenDate) {
            StatisticalData statisticalData = new StatisticalData();
            statisticalData.setTime(time);
            statisticalData.setTotal(0);
            resultList.add(statisticalData);
        }

        List<StatisticalData> mapperList =  dangerSituationManageMapper.getXqTjListByQuarterQxrw(startDate,endDate);
        if (CollectionUtils.isEmpty(mapperList)){
            return resultList;
        }
        for (StatisticalData statisticalData : mapperList) {
            String time = statisticalData.getTime();
            for (StatisticalData data : resultList) {
                if (time.equals(data.getTime())){
                    data.setTotal(statisticalData.getTotal());
                }
            }
        }
        return resultList;
    }

    private List<StatisticalData> getXunQiBetweenDateQxrw(String startDate,String endDate){
        ArrayList<StatisticalData> resultList = new ArrayList<>();
        List<String> yearBetweenDate = DateUtil.getYearBetweenDate(startDate, endDate);
        for (String year : yearBetweenDate) {
            String  startTime =  year+"-07-01";
            String  endTime =  year+"-10-01";
            StatisticalData data =  dangerSituationManageMapper.getXqTjListByXunQiQxrw(startTime,endTime);
            data.setTime(year);
            resultList.add(data);
        }
        return resultList;
    }
}
